<?php
// +-------------------------------------------------------------------------------
// | DingZone [ A Rapid Development Framework For Dingtalk ]
// +-------------------------------------------------------------------------------
// | 站点模块挂件 v1.0
// |
// | Copyright (c) 2014-2018 http://www.heimalanshi.com All rights reserved.
// | Author : Jie
// | Date : 2018-08-09
// +-------------------------------------------------------------------------------

namespace app\core\model;

use think\Model;

class SiteModuleWidget extends Model {

    /**
     * 宽度解析
     *
     * @param $width
     * @return array
     */
    public static function parseWidth($width) {
        if (is_numeric($width)) {
            $width = intval($width);
            return [$width, $width, $width, $width];
        }
        $widths = json_decode($width);
        if (empty($widths)) {
            return [2, 2, 2, 2];
        }
        if (count($widths) == 1) {
            return [$widths[0], $widths[0], $widths[0], $widths[0]];
        }
        if (count($widths) == 2) {
            return [$widths[0], $widths[1], $widths[1], $widths[1]];
        }
        if (count($widths) == 3) {
            return [$widths[0], $widths[1], $widths[2], $widths[2]];
        }
        return [$widths[0], $widths[1], $widths[2], $widths[3]];
    }

    /**
     * 增加模块widgets
     *
     * @param $mid
     * @param $widgets
     */
    public static function createWidgets($mid, $widgets) {
        foreach ($widgets as $widget) {
            $data = [
                'module_id' => $mid,
                'name' => $widget['name'],
                'pushToModuleHome' => $widget['pushToModuleHome'],
                'pushToGlobalHome' => $widget['pushToGlobalHome'],
                'width' => $widget['width'],
                'sort' => $widget['sort']
            ];
            self::create($data);
        }
    }

    /**
     * 获取模块所有的可配置选项
     *
     * @param $mid
     * @return false|static[]
     * @throws \think\exception\DbException
     */
    public static function getWidgets($mid) {
        $dao = new self();
        $widgetObjs = $dao->where([
            'module_id' => $mid
        ])->order("sort desc")->select();
        $widgets = [];
        foreach ($widgetObjs as $widgetObj) {
            $widgets[] = $widgetObj->getData();
        }
        return $widgets;
    }

    /**
     * 删除模块相关的全部菜单和入口
     *
     * @param $mid
     * @return int
     */
    public static function deleteByMid($mid) {
        $query = new self();
        return $query->where(['module_id' => $mid])->delete();
    }
}